/** *******************************************************************
 * FlexDatabaseManager
 * Copyright (c) 2008 Jonnie Spratley. All Rights Reserved.
 * @author  Jonnie Spratley
 * @contact jonniespratley@gmail.com
 * @internal
 ******************************************************************* */
package com.jonniespratley.flexdatabasemanager.commands.tables
{
	import com.adobe.cairngorm.commands.ICommand;
	import com.adobe.cairngorm.control.CairngormEvent;
	import com.adobe.serialization.json.JSON;
	import com.jonniespratley.flexdatabasemanager.business.FlexDatabaseManagerDelegate;
	import com.jonniespratley.flexdatabasemanager.events.tables.OptimizeTableEvent;
	import com.jonniespratley.flexdatabasemanager.model.ModelLocator;
	import com.jonniespratley.flexdatabasemanager.vo.*;
	
	import mx.controls.Alert;
	import mx.rpc.IResponder;
	import mx.rpc.events.FaultEvent;
	import mx.rpc.events.ResultEvent;

	public class OptimizeTableCommand implements ICommand, IResponder
	{
		private var model:ModelLocator = ModelLocator.getInstance();

		public function execute( event:CairngormEvent ) : void
		{
			model.interactingWithServer = true;
			
			var evt:OptimizeTableEvent = event as OptimizeTableEvent;
			
			var delegate:FlexDatabaseManagerDelegate = new FlexDatabaseManagerDelegate( this );
			
			if ( model.selectedDatabase == null && model.selectedTableStatus == null )
			{
				//alert the user and stop
				Alert.show( 'Please select a database and/or table before checking table.', 'Alert' );
				
			} else {
				
				delegate.optimizeTable( model.currentUser, model.selectedDatabase, model.selectedTableStatus );
			}
		}
		
		public function result( data:Object ) : void
		{
			model.interactingWithServer = false;
			
			var resultObj:ResultEvent = data as ResultEvent;
			if ( resultObj.result is String )
			{
				var rawData:String = String( resultObj.result ); 
				var tempArray:Array = ( JSON.decode( rawData ) as Array );
				var tableCheck:TableCheckVO = new TableCheckVO( tempArray[ 0 ] );	
				
				model.tableCheck = tableCheck;
			}
		//	Alert.show( rawData );
		}

		public function fault( fault:Object ):void
		{
			model.interactingWithServer = false;
			
			var faultEvt:FaultEvent = fault as FaultEvent;
			
			Alert.show(faultEvt.fault.toString(), "Error");
			
			trace(faultEvt.fault.faultString);
		}
	}
}